package com.lanqiao.attendance.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.lanqiao.attendance.mapper.ClassMapper;
import com.lanqiao.attendance.mapper.StudentMapper;
import com.lanqiao.attendance.pojo.Student;
import com.lanqiao.attendance.service.StudentService;
import com.lanqiao.attendance.utils.FileUtils;
import com.lanqiao.attendance.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import static com.baomidou.mybatisplus.core.toolkit.Wrappers.update;

@Slf4j
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    StudentMapper studentMapper;
    @Autowired
    private FileUtils fileUtils;

    @Autowired
    ClassMapper classMapper;

    @Override
    public PageInfo<Student> queryAllStu(PageParam pageParam) {
        Page page = PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        List<Student> list = studentMapper.queryAllStu();
        List<StudentVo> voList = new ArrayList<>();
        for (Student student : list) {
            StudentVo studentVo = new StudentVo();
            studentVo.setId(student.getId());
            studentVo.setAccount(student.getAccount());
            studentVo.setClassName(student.getClassName());
            studentVo.setGender(student.getGender());
            studentVo.setMajor(student.getMajor());
            studentVo.setSchool(student.getSchool());
            studentVo.setName(student.getName());
            voList.add(studentVo);
        }
        PageInfo<Student> pageInfo = new PageInfo<>(page.getResult());
        return pageInfo;
    }

    @Override
    public Student login(String account, String password) {
        return studentMapper.login(account, password);
    }

    @Override
    public int insertStudent(Student student) {
        String str = "shzu";
        String password = DigestUtils.md5Hex(student.getPassword() + str);
        student.setPassword(password);
        int i = studentMapper.insertStudent(student);
        return i;
    }

    @Override
    public List<Student> queryStuByName(String name) {
        return studentMapper.queryStuByName(name);
    }

    @Override
    public Student queryStuByAccount(String account) {
        return studentMapper.queryStuByAccount(account);
    }

    @Override
    public int updateStuClass(String className, long id) {
        return studentMapper.updateStuClass(className, id);
    }

    @Override
    public Student queryStuById(long id) {
        return studentMapper.queryStuById(id);
    }

    @Override
    public ClassVo queryClass(String name) {
        return studentMapper.queryClass(name);
    }

    @Override
    public int delStuById(String account) {
        return studentMapper.delStuById(account);
    }

    @Override
    public int updateStuByAccount(Student student) {
        String str = "shzu";
        String password = DigestUtils.md5Hex(student.getPassword() + str);
        student.setPassword(password);
        return studentMapper.updateStuByStu(student);
    }

    @Override
    public int updateStuByTea(Student student) {
        return studentMapper.updateStuByTea(student);
    }

    @Override
    public Student queryStuByIdPart(long id) {
        return studentMapper.queryStuByIdPart(id);
    }

    @Override
    public List<Student> queryStuByClsName(String className) {
        return studentMapper.queryStuByClsName(className);
    }


    @Override
    public Result modify(MultipartFile headImg, long id) {
        // 校验图片格式
        if (!imageTypeRight(headImg)) return Result.fail(-999, "图片格式不正确");
        // 获取上传文件后的路径
        String path = uploadFile(headImg);
        Student student = queryStuById(id);
        // 删除之前的头像(如果是默认头像不删除)
        String image = student.getHeadImg();
        if (!image.equals("static/default.png")) {
            if (!fileUtils.del(image.substring(path.indexOf("/") + 1))) {
                log.info("修改头像时, 原来的头像删除失败");
            } else {
                log.info("修改头像时, 原来的头像删除成功");
            }
        }
        // 修改数据库中头像的路径信息
        update(Wrappers.<Student>lambdaUpdate()
                .set(Student::getHeadImg, path)
                .eq(Student::getName, student.getName()));
        // 该路径为图片相对路径 可放在url中的服务后面 进行访问
        // 比如: http://localhost:9000/cloudos-opt/headimage/01c8806dc26d45539b53c22c766cd250.jpg
        // http://localhost:9000/cloudos-opt/static/default.png
        return Result.success("修改成功", path);
    }

    @Override
    public Student queryStuBysAccount(String account) {
        Student student = studentMapper.queryStuByAccount(account);
        return student;
    }

    @Override
    public void updateHeadImg(String account, String headImg) {
        studentMapper.updateHeadImg(account, headImg);
    }

    @Override
    public List<Student> queryAllNoClass() {
        return studentMapper.queryAllNoClass();
    }

    @Override
    @Transactional
    public Result addToClass(StudentListVo studentListVo) {
        Long [] ids = studentListVo.getIds();

        if(ids.length ==0){
            return Result.fail(333,"没有选择学生，插入失败");
        }
        String className = studentListVo.getCurrentClassName();
        int number = studentMapper.countStudent(className);
        number += ids.length;
        classMapper.changeNum(className,number);
        int row = 0;
        for (int i = 0; i <ids.length ; i++) {
            row= studentMapper.addToClass(ids[i],className);
        }
           return Result.success("加入班级成功",null);
    }

    @Override
    public Result rmFromClass(StudentListVo studentListVo) {
        Long [] ids = studentListVo.getIds();

        if(ids.length ==0){
            return Result.fail(333,"没有选择学生，移出失败");
        }
        String className = studentListVo.getCurrentClassName();
        int number = studentMapper.countStudent(className);
        number -= ids.length;
        classMapper.changeNum(className,number);
        for (int i = 0; i <ids.length ; i++) {
            studentMapper.rmFromClassById(ids[i]);
        }
        return Result.success("移出班级成功",null);
    }

    @Override
    public List<Student> queryAllByClass(String className) {
        return studentMapper.queryAllByClass(className);
    }

    @Override
    public void updateClassName(String oldName, String newName) {
        studentMapper.updateClassName(oldName,newName);
    }

    @Override
    public void rmFromClassByName(String className) {
        studentMapper.rmFromClassByName(className);
    }


    /**
     * 验证图片的格式
     *
     * @param file 图片
     * @return
     */
    private boolean imageTypeRight(MultipartFile file) {
        // 首先校验图片格式
        List<String> imageType = Lists.newArrayList("jpg", "jpeg", "png", "bmp", "gif");
        // 获取文件名，带后缀
        String originalFilename = file.getOriginalFilename();
        // 获取文件的后缀格式
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();  //不带 .
        if (!imageType.contains(fileSuffix)) return false;
        return true;
    }

    /**
     * 上传文件
     *
     * @param file
     * @return 返回路径
     */
    public String uploadFile(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        // 只有当满足图片格式时才进来，重新赋图片名，防止出现名称重复的情况
        String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileSuffix;
        // 该方法返回的为当前项目的工作目录，即在哪个地方启动的java线程
        File fileTransfer = new File(fileUtils.getPath(), newFileName);
        try {
            file.transferTo(fileTransfer);
            log.info("头像上传: " + fileTransfer.getPath());
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 将图片相对路径返回给前端
        return "headimage/" + newFileName;
    }


}
